import Vue from 'vue'
import trim from 'lodash.trim'
import Store from '../../store'

/*
使用
<el-button v-action="'test: ADD, DELETE'" primary>add</el-button>
*/
Vue.directive('action', {
    inserted: function (el, binding, vnode) {
    // 判断是否存在这个 操作的权限
        const [permissionName, action] = binding.value.split(':')
        const value = action.replace(/(\[)|(\])/g, '').split(',')
        const list = Store.state.permission.permissions[permissionName] || []
        const hasPermission = value.every((action) => {
            return !trim(action) ? true : list.includes(trim(action))
        })
        if (!hasPermission) {
            (el.parentNode && el.parentNode.removeChild(el)) ||
        (el.style.display = 'none')
        }
    }
})

// 拖动弹框

Vue.directive('dragable', {
    bind: function (el, binding, vnode) {
        const headerEl = el.querySelector('.el-dialog__header')
        const dialogDom = el.querySelector('.el-dialog')
        let elStartX, elStartY
        headerEl.onmousedown = (e) => {
            elStartX = dialogDom.offsetLeft
            elStartY = dialogDom.offsetTop
            const mouseStartX = e.clientX
            const mouseStartY = e.clientY
            document.onmousemove = (e) => {
                const mouseClientX = e.clientX
                const mouseClientY = e.clientY
                const xGap = mouseClientX - mouseStartX
                const yGap = mouseClientY - mouseStartY
                dialogDom.style.left = elStartX + xGap + 'px'
                dialogDom.style.top = elStartY + yGap + 'px'
            }
            document.onmouseup = () => {
                document.onmouseup = null
                document.onmousemove = null
            }
        }
    }
})
